package cmd

import (
	"fmt"
	"gitee.com/feimos/dm/core"
	"gitee.com/feimos/dm/dup"
	"gitee.com/feimos/dm/utils"
	"github.com/urfave/cli/v2"
	"log"
	"strconv"
	"path/filepath"
)

// DupCommand 处理 dup subcommand
func DupCommand(c *cli.Context) error {

	name := utils.UnifyExtname(core.UnifyPath(c.Args().First()))

	if len(name) == 0 {
		return fmt.Errorf("missing param of ext name, example: \"dm dup .docx\"")
	}

	noRun := c.Bool("no-run")

	var removedFiles []dup.FileInfo

	err := dup.Run([]string{name}, &removedFiles, !noRun)
	if err != nil {
		return err
	}

	if len(removedFiles) > 0 {
		data := GenerateDupInfo(removedFiles)

		utils.PrintDupInfo(data)

		if !noRun {
			log.Printf("try to run command \"dm update %v\" subsequently\n", name)
		} else {
			log.Printf("check the list and run command \"dm dup %v\" subsequently\n", name)
		}
	} else {
		log.Printf("task finished and find none to remove\n")
	}

	return nil
}

func GenerateDupInfo(infos []dup.FileInfo) [][]string {
	var res [][]string

	var sumSize uint64

	for index, info := range infos {
		item := make([]string, 3)

		item[0] = strconv.Itoa(index + 1)
		item[1] = filepath.Base(info.Path)
		item[2] = utils.FormatFileUint(info.Size)
		sumSize += info.Size
		res = append(res, item)
	}

	item := make([]string, 3)

	item[0] = "*"
	item[1] = "SUM OF SIZE"
	item[2] = utils.FormatFileUint(sumSize)

	res = append(res, item)

	return res
}
